package com.asurplus.timer.task;

import cn.hutool.core.collection.CollectionUtil;
import com.asurplus.common.redis.RedisConst;
import com.asurplus.common.redis.RedisUtil;
import com.asurplus.system.entity.SysDictDetail;
import com.asurplus.system.mapper.SysDictDetailMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目启动任务--将数据字典存入Redis
 *
 * @Author Lizhou
 **/
@Component
@Order(200)
public class SystemDictStartTask implements CommandLineRunner {

    @Autowired
    private SysDictDetailMapper sysDictDetailMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Value("${spring.profiles.active}")
    public String profiles;

    @Override
    public void run(String... args) throws Exception {
        // 如果是开发环境，就不需要执行
        if ("dev".equals(profiles)) {
            return;
        }
        List<SysDictDetail> list = sysDictDetailMapper.listSysDictDetailOnSystemStart();
        if (null != list && !list.isEmpty()) {
            Map<Object, Map<Object, Object>> map = new HashMap<>();
            list.forEach(i -> {
                if (CollectionUtil.isEmpty(map.get(i.getDictCode()))) {
                    map.put(i.getDictCode(), new HashMap<>());
                }
                map.get(i.getDictCode()).put(i.getCode(), i.getName());
            });
            // 批量存入
            for (Object item : map.keySet()) {
                redisUtil.setHashMap(RedisConst.Key.SYS_DICT + item, map.get(item));
            }
        }
    }
}
